<template>
  <div class="tree-wrap">
    <div class="toggle-bar" @click="toggleSwitch()">
      <span>目标</span>
      <i v-show="isShow" class="el-icon-arrow-down"></i>
      <i v-show="!isShow" class="el-icon-arrow-right"></i>
    </div>
    <div v-show="isShow" class="tree-box">
      <el-input
        v-model="tableParams.name"
        size="default"
        placeholder="搜索"
        clearable
        @blur="searchClick(tableParams.name)"
        @keyup.enter.native="searchClick(tableParams.name)"
      >
      </el-input>
      <el-form :model="tableParams" :inline="true" @submit.native.prevent>
        <div class="search-box">
          <el-select
            style="margin-right: 10px"
            v-model="tableParams.direction"
            placeholder="选择方向"
            clearable
            filterable
            @change="searchClick(tableParams.direction)"
          >
            <el-option
              v-for="item in directionList"
              :key="item"
              :value="item"
              :label="item"
            >
            </el-option>
          </el-select>
          <el-select
            style="margin-right: 10px"
            v-model="tableParams.city"
            placeholder="选择城市"
            clearable
            filterable
            @change="searchClick(tableParams.city)"
          >
            <el-option
              v-for="item in cityList"
              :key="item"
              :value="item"
              :label="item"
            >
            </el-option>
          </el-select>
          <el-select
            style="margin-right: 10px"
            v-model="tableParams.industry"
            placeholder="选择行业"
            clearable
            filterable
            @change="searchClick(tableParams.industry)"
          >
            <el-option
              v-for="item in industryList"
              :key="item"
              :value="item"
              :label="item"
            >
            </el-option>
          </el-select>
        </div>
      </el-form>
      <div class="grid-content">
        <el-table
          ref="mytable"
          class="vul-table"
          :data="tableData"
          max-height="400"
          size="small"
          row-key="id"
          :expand-row-keys="expandID"
          :row-style="rowClass"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @row-click="handleRowClick"
          @selection-change="handleSelectionChange"
          @header-click="headerClick"
        >
          <el-table-column
            label="目标名称"
            prop="name"
            show-overflow-tooltip
            min-width="180"
          >
            <template v-slot:default="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="完整性" prop="richLevel" align="center">
            <template v-slot:default="scope">
              <el-tooltip
                class="item"
                effect="dark"
                :content="
                  scope.row.richLevel === 1
                    ? lowTitle
                    : scope.row.richLevel === 2
                    ? centreTitle
                    : tallTitle
                "
                placement="bottom-end"
              >
                <img
                  v-if="scope.row.richLevel === 1"
                  src="@/static/images/c.svg"
                  alt=""
                  class="iconImg"
                />
                <img
                  v-if="scope.row.richLevel === 2"
                  src="@/static/images/b.svg"
                  alt=""
                  class="iconImg"
                />
                <img
                  v-if="scope.row.richLevel === 3"
                  src="@/static/images/a.svg"
                  alt=""
                  class="iconImg"
                />
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column label="方向" prop="direction" />
          <el-table-column label="城市" prop="city" />
          <el-table-column label="行业" prop="industry" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  defineProps,
  defineEmits,
  ref,
  reactive,
  onMounted,
  watchEffect,
  nextTick,
} from 'vue';
import { useStore } from 'vuex';
const store = useStore();
const emit = defineEmits(['checkClick']);
const props = defineProps({
  paramsData: {
    type: Object,
    default: () => {
      return {};
    },
  },
});
const expandID = ref<any>([]);
const multipleSelection = ref<any>([]);
const isShow = ref(true);
const loading = ref(false);
const tableData = ref<any[]>([]);
const mytable = ref<any>(null);
const tableParams = reactive({
  name: '',
  direction: '',
  city: '',
  industry: '',
  pageNumber: 1,
  // pageSize: 10,
});
const total = ref(0);
const isLoading = ref(false);
const directionList = ref([]);
const cityList = ref([]);
const industryList = ref([]);
const checkedList = ref<any>([]);
const lowTitle = ref(
  '收集的信息在对目标已知网络资产中存在部分遗漏，信息系统、域名、IP地址等网络资产中的关键字段存在一定程度缺失',
);
const centreTitle = ref(
  '收集的信息基本覆盖了已知的网络资产，包括信息系统、域名、IP地址，评分得到60分以上',
);
const tallTitle = ref(
  '收集的信息全面覆盖了所有已知的网络资产，包括信息系统、域名、IP地址，评分得到80分以上',
);

watchEffect(() => {
  checkedList.value = [];
  if (multipleSelection.value.length > 0) {
    multipleSelection.value.forEach((item, index) => {
      checkedList.value.push(item.name);
    });
  }
});
onMounted(() => {
  pageCom('');
  directionType();
  cityType();
  industryType();
});
const filterTree = (data, keyword) => {
  const result:any[] = [];
  data.forEach((item) => {
    const newItem = { ...item };

    if (newItem.children) {
      // 如果有子节点，则递归过滤子节点
      newItem.children = filterTree(newItem.children, keyword);
    }

    if (
      newItem.name.includes(keyword) ||
      newItem.direction.includes(keyword) ||
      newItem.city.includes(keyword) ||
      newItem.industry.includes(keyword)
    ) {
      // 如果节点名称包含查询关键字，则添加到结果中
      result.push(newItem);
      expandID.value.push(`${newItem.id}`);
    } else if (newItem.children && newItem.children.length > 0) {
      // 如果子节点有匹配的项，则添加到结果中
      expandID.value.push(`${newItem.id}`);
      result.push(newItem);
    }
  });
  return result;
};

const toggleSwitch = () => {
  isShow.value = !isShow.value;
};
const pageCom = async (keyword) => {
  // this.isLoading = false
  const { code, data } = await store.dispatch('expose/pageCom', tableParams);
  // this.isLoading = true
  if (code === 0) {
    if (keyword) {
      tableData.value = filterTree(data, keyword);
    } else {
      tableData.value = data;
    }

    // if (this.tableParams.pageNumber != 1) {
    //   this.tableData.push(...data.list)
    // } else {
    //   this.tableData = data.children
    // }
    // this.total = Number(data.total)
  }
};
const searchClick = (keyword) => {
  pageCom(keyword);
};
const rowClass = ({ row, rowIndex }) => {
  if (checkedList.value.includes(row.name)) {
    return { 'background-color': '#0289f7' };
  }
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const handleRowClick = (row, event, column) => {
  const name = row.name;
  const index = checkedList.value.indexOf(name);
  if (index > -1) {
    mytable.value.setCurrentRow();
    checkedList.value.splice(index, 1);
  } else {
    checkedList.value.push(name);
  }

  const strVal = `(company=="${name}")`;
  emit('checkClick', strVal, index > -1);
};
const headerClick = (column, event) => {
  if (column.label === '完整性') {
    store.dispatch('expose/calculateRichness');
  }
};
const directionType = async () => {
  directionList.value = await selectedList('direction');
};
const cityType = async () => {
  cityList.value = await selectedList('city');
};
const industryType = async () => {
  industryList.value = await selectedList('industry');
};
const selectedList = async (type) => {
  const { code, data } = await store.dispatch('expose/selectedList', {
    type,
  });
  if (code === 0) {
    return data;
  }
};
const handleScroll = () => {
  nextTick(() => {
    if(mytable.value){
      mytable.value.bodyWrapper.addEventListener(
      'scroll',
      (res) => {
        const height = res.target;
        const clientHeight = height.clientHeight;
        const scrollTop = height.scrollTop;
        const scrollHeight = height.scrollHeight;

        if (clientHeight + scrollTop + 50 >= scrollHeight && isLoading.value) {
          if (total.value > tableData.value.length) {
            tableParams.pageNumber++;
            // this.pageCom()
          } else {
            // this.tableData.push({ address: '加载完毕', name: '加载完毕' })
            isLoading.value = false;
          }
        }
      },
      true,
    );
    }
  
  });
};
</script>
<style lang="scss" scoped>
.tree-wrap {
  margin: 0px 12px;
  padding: 10px 0;
  // border-bottom: 1px solid #3a404d;

  .toggle-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
    // padding-bottom: 8px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 600;
  }

  .tree-box {
    .icon {
      cursor: pointer;
    }

    .search-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 10px;
    }

    .iconImg {
      width: 20px;
      height: 20px;
    }

    .grid-content {
      // height: 400px;
      background-color: $-white;
      padding: 10px;
      border-radius: 4px;
    }
  }

  .line {
    border-bottom: 1px solid #3a404d;
  }

  ::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
    background: transparent;
  }

  ::v-deep .el-table .el-table__cell .cell {
    line-height: 20px;
    height: 20px;
  }

  ::v-deep
    .el-table
    tbody
    tr
    td:first-child:not(.el-table-column--selection)
    .cell {
    padding-left: 0px;
  }

  ::v-deep
    .el-table
    thead
    th:first-child:not(.el-table-column--selection)
    .cell {
    padding-left: 0px;
  }

  ::v-deep .el-table .el-table__expand-icon {
    transform: rotate(-90deg);
  }

  // 修改表格树图标
  ::v-deep
    .el-table
    .el-table__cell
    .cell
    .el-table__expand-icon
    .el-icon-arrow-right::before {
    content: '\e60c';
    font-family: 'raderfont';
    font-size: 12px;
  }
}
</style>
